package com.dds.system.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.dds.common.config.AliyunConfig;
import com.dds.common.utils.uuid.UUID;
import com.dds.system.service.FileService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * @author gaolianjie
 * @create 2021/4/9
 */
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private AliyunConfig aliyunConfig;

    @Override
    public String uploadFileToOss(MultipartFile file) {
        OSS ossClient = new OSSClientBuilder().build(
                aliyunConfig.getOssEndpoint(),
                aliyunConfig.getOssAccessId(),
                aliyunConfig.getOssAccessKey()
        );
        try {
            String fileExt = FilenameUtils.getExtension(file.getOriginalFilename());
            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;

            PutObjectRequest putObjectRequest = new PutObjectRequest(
                    aliyunConfig.getOssBucket(),
                    fileName,
                    new ByteArrayInputStream(file.getBytes())
            );

            ossClient.putObject(putObjectRequest);

            return "https://" + aliyunConfig.getOssBucket() + "." +
                    ossClient.getBucketInfo(aliyunConfig.getOssBucket()).getBucket().getExtranetEndpoint()
                    + "/" + fileName;

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }

        return null;
    }
}
